#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent),
    ui(new Ui::Widget) ,
    m_thread(new WorkThread()){
  ui->setupUi(this);
  this->setWindowTitle("UDP客户端");
  connect(m_thread.get(), &WorkThread::showMessage, this, &Widget::showMessage);
}

Widget::~Widget() {
  m_thread->stopThread();
  m_thread->wait();
  delete ui;
}

void Widget::showMessage(const QString &info) {
  ui->messageShoxEdit->appendPlainText(info);
}

void Widget::on_btnSend_clicked() {
  if(!m_start){
      QString ip = ui->lineEditIP->text();
      uint port = ui->lineEditPort->text().toUInt();
      m_thread->setAddr(QHostAddress(ip),port);
      m_thread->start();
      m_start = true;
      QThread::sleep(1); //等待线程启动
  }

  // 获取要发送的内容
  QString msg = ui->messageEdit->text();
  QByteArray data = msg.toUtf8(); // 转换为utf8字节数组
  m_thread->sendData(data);
}
